<?php defined('SYSPATH') or die('No direct script access.');
	
	class Controller_Analysis extends Controller {
						
		public function exception(){}
			
		public function action_index(){
			$view = View::factory("analysis/analysis-list");
			$grid = new Jqgrid("analysis", Helper_Service::factory("analysis"));
			$view->analysis_list = $grid->render("jqgrid/config/analysis"); 
			
			$this->request->response = $view->render();
		}
		
		public function action_list(){
			$grid = new Jqgrid("analysis", Helper_Service::factory("analysis"));
			
			$criteria = new Jqgrid_Criteria();
			$criteria->page = $_POST['page'];
			$criteria->limit = $_POST['rows'];
			$criteria->sidx = $_POST['sidx'];
			$criteria->sord = $_POST['sord'];
			
			if (isset($_POST['_search'])){
				if (($search = $_POST['_search']) == "true"){
					$criteria->isSearch = true;
					$criteria->searchField = $_POST['searchField'];
					$criteria->searchOper = $_POST['searchOper'];
		 			$criteria->searchString = $_POST['searchString'];
				}
			}
			
			$this->request->response = $grid->getList($criteria);
		}
	
		public function action_get(){
			$id_analysis = (isset($_POST['id']))? $_POST['id'] : $this->request->param("id");
			$analysis_service = Helper_Service::factory("analysis",$id_analysis);
						
			$actions = array();
			$actions[] = array("url"=>"/diastole/analysis/parameters/$id_analysis","text"=>"Parametros");
			//$actions[] = array("url"=>"/diastole/analysis/clinical/$id_analysis","text"=>"Datos Clinicos");
			$actions[] = array("url"=>"/diastole/analysis/segments/$id_analysis","text"=>"Segmentos");
			$actions[] = array("url"=>"/diastole/analysis/preview/$id_analysis","text"=>"Informe");
			$actions[] = array("url"=>"/diastole/analysis/comments/$id_analysis","text"=>"Comentarios");
			$actions[] = array("url"=>"/diastole/analysis/conclusions/$id_analysis","text"=>"Conclusiones");
			$actions[] = array("url"=>"/diastole/analysis/export/$id_analysis","text"=>"Exportar");
			
			//Tabs creation
			$new_tabs = View::factory("components/tabs");
			$new_tabs->actions = $actions;
			
			$analysis_form = View::factory("analysis/analysis-form");
			$analysis_form->patient_name = $analysis_service->getPatient()->getFullname();
			$analysis_form->analysis_content = $new_tabs->render();
			
			$this->request->response = $analysis_form->render();
		}
		
		public function action_save(){
			//$grid = new Jqgrid("samplingperiod", Helper_Service::factory("samplingperiod"));
			//$this->request->response = $grid->save($_POST['oper'],$_POST);
			$this->request->response = Helper_Service::factory("analysis")->save(intval($_POST['id']),$_POST);
		}
		
		
		public function action_add(){
			//$this->request->response = View::factory("components/patientform")->set("patient_id",0)->render();
		}
			
		/*Pestaña Parametros*/
		public function action_parameters(){
			
			$analysis = Helper_Service::factory("analysis",$this->request->param("id"));
			
			$segment = $analysis->getFinalSegment();
			$results = $analysis->getResults();
						
			$view = View::factory("page");
			
			$param_view = View::factory("analysis/parameters");
			$param_view->params = array('aod_value'=>$results->getDiastolicWaveAmp()->value,
										'iar_value'=>$results->getRadialAugmentation()->value,
										'aos_value'=>$results->getSystolicWaveLength()->value,
			                            'imc_value'=>$analysis->getClinicalData()->calculateIMC(),
			                            'fc_value'=>$results->getHeartRate());
			
			$param_view->signal = array('sampling_period'=>$analysis->getPeriod()->k_value,
										'num_samples'=>$segment->length,
										'max_value'=>$segment->max,
										'min_value'=>$segment->min);
			
			$view->page_content = $param_view->render(); 
			
			$view->scripts = array(	'media/js/jqplot/jquery.jqplot.min.js',
									'media/js/jqplot/plugins/jqplot.canvasTextRenderer.min.js',
									'media/js/jqplot/plugins/jqplot.canvasAxisLabelRenderer.min.js',
									'media/js/jqplot/plugins/jqplot.canvasAxisTickRenderer.min.js',
									'media/js/jqplot/plugins/jqplot.highlighter.min.js',
									'media/js/jqplot/plugins/jqplot.cursor.min.js',
									'media/js/jqplot/plugins/jqplot.dateAxisRenderer.min.js',
									'media/js/js_controls/js_chart_settings.js',
									'media/js/js_controls/js_chart_series.js',
									'media/js/js_controls/js_chart.js');
			
			
			$user_script = View::factory('js-user-scripts/final-segment');
			$user_script->chart_data = $segment->toJSON(floatval($analysis->getPeriod()->k_value));
			$user_script->aod_data = $results->getDiastolicWaveAmp()->toJSON();
			$user_script->aos_data = $results->getSystolicWaveLength()->toJSON();
			$user_script->iar_data = $results->getRadialAugmentation()->toJSON(); 
			$user_script->t_data = $results->getSystolicReflexOffset()->toJSON();
			
			$view->user_script = $user_script->render();
			
			
			$this->request->response = $view->render();
					
		}
		
		/*Pestaña información clinica*/
		public function action_clinical(){
			
		}
		
		/***********************************Pestaña Segmentos Seleccionados******************************/
		public function action_segments(){
			$id_analysis = $this->request->param("id");
			$segments_service = Helper_Service::factory("analysis",$id_analysis)->getSelectedSegments();
			$segments = $segments_service->getSelectedSegment(); //devuelve un array de dao_selectedsegment
						
			$selected_segments = array();
			foreach ($segments as $current_seg){
				array_push($selected_segments, array("id"=>$current_seg->id, "number"=>$current_seg->number));
			}

			$segments_view = View::factory("analysis/selected-segments");
			$segments_view->selected_segments = $selected_segments;
			$segments_view->data_url = "/diastole/analysis/getsegmentdata/$id_analysis/";
			$segments_view->thumb_url = "/diastole/plotter/selectedsegmenthumb/$id_analysis/";
			$segments_view->scripts = array('media/js/jqplot/jquery.jqplot.min.js',
											'media/js/jqplot/plugins/jqplot.canvasTextRenderer.min.js',
											'media/js/jqplot/plugins/jqplot.canvasAxisLabelRenderer.min.js',
											'media/js/jqplot/plugins/jqplot.canvasAxisTickRenderer.min.js',
											'media/js/jqplot/plugins/jqplot.highlighter.min.js',
											'media/js/jqplot/plugins/jqplot.cursor.min.js',
											'media/js/jqplot/plugins/jqplot.dateAxisRenderer.min.js',
											'media/js/js_controls/js_chart_settings.js',
											'media/js/js_controls/js_chart_series.js',
											'media/js/js_controls/js_chart.js',
											'media/js/js_controls/js_carousel.js');
			
			$first_segment = $segments_service->getSegmentData($segments[0]->segment);
			$js_controller = View::factory("js-user-scripts/selected-segments")->set("chart_data",$first_segment->toJSON());
			$segments_view->js_user_script = $js_controller->render();
			
			$this->request->response = $segments_view->render();
		}
		
		public function action_getsegmentdata(){
			$id_analysis = $this->request->param("id");
			$id_segment = $this->request->param("id2");	
			$segments_service = Helper_Service::factory("analysis",$id_analysis)->getSelectedSegments();
			$selected = $segments_service->getSelectedSegment($id_segment);
			$segment_data = $segments_service->getSegmentData($selected->segment);
			$this->request->response = $segment_data->toJSON();
		}
				
						
		/**********************************Pestaña Comentarios*********************************************/
		public function action_comments(){
			$id_analysis = $this->request->param("id");
			$comments = Helper_Service::factory("comment")->getList();
			$template = $this->factoryTemplate("Comentarios",
												$comments,
												"/diastole/analysis/getcommentlist",
												"/diastole/analysis/getcomment",
												"/diastole/analysis/newcomment",
												"/diastole/analysis/savereportcomment/$id_analysis",
												Helper_Service::factory("analysis",$id_analysis)->getReport()->getComments()																							
												);
			$this->request->response = $template->render();
		}
				
		public function action_getcommentlist(){
			$templates = $this->filteredTemplates($filter=$_POST['filter'],Helper_Service::factory("comment"));
						
			$dataset = array();
			foreach($templates as $template){
				$dataset[]= "{'id':'".$template->id."','value':'".$template->comment_name."'}";
			}

			$this->request->response = $this->jsonTemplates($dataset); 
			
		}
		
		public function action_getcomment(){
			if (!($id=$_POST['id'])) $template = "{'template':''}";
			else{
				$comment = Helper_Service::factory("comment")->get($id);
				$template = "{'template':'".$comment->comment."'}";
			}
			$this->request->response = $template;
		}
		
		public function action_newcomment(){
			$this->request->response = $this->newTemplate("Comentarios","/diastole/analysis/savecomment")->render();
		}
		
		public function action_savecomment(){
			$data = array();
			$data['comment_name'] = $_POST['template_name']; 
			$data['comment'] = $_POST['template_description']; 
			
			if (($applicable = $_POST['applicable']) == "all"){	$data['female'] = 1;$data['male'] = 1;}
			elseif ($applicable == "male"){$data['female'] = 0;$data['male'] = 1;}
			else{ $data['female'] = 1;$data['male'] = 0;}
						
			$id = Helper_Service::factory("comment")->save(0,$data);
			$this->request->response = $this->savedTemplateResponse(true,"Plantilla de Comentario Guardada con Exito")->render();
		}
		
		public function action_savereportcomment(){
			$id_analysis = $this->request->param("id");
			$comments = $_POST["content"];
			$this->request->response = Helper_Service::factory("analysis",$id_analysis)->getReport()->saveComments($comments);
		}
		
		
		/*********************************************Pestaña Conclusiones***************************************/
		public function action_conclusions(){
			$id_analysis = $this->request->param("id");
			Fire::log($id_analysis);
			$conclusions = Helper_Service::factory("conclusion")->getList();
			$template = $this->factoryTemplate("Conclusiones",
												$conclusions,
												"/diastole/analysis/getconclusionlist",
												"/diastole/analysis/getconclusion",
												"/diastole/analysis/newconclusion",
												"/diastole/analysis/savereportconclusion/$id_analysis",
												Helper_Service::factory("analysis",$id_analysis)->getReport()->getConclusion()											
												);
			$this->request->response = $template->render();
		}
		
		
		public function action_getconclusionlist(){
			$templates = $this->filteredTemplates($filter=$_POST['filter'],Helper_Service::factory("conclusion"));
						
			$dataset = array();
			foreach($templates as $template){
				$dataset[]= "{'id':'".$template->id."','value':'".$template->conclusion_name."'}";
			}

			$this->request->response = $this->jsonTemplates($dataset); 
		}
		
		public function action_getconclusion(){
			if (!($id=$_POST['id'])) $template = "{'template':''}";
			else{
				$conclusion = Helper_Service::factory("conclusion")->get($id);
				$template = "{'template':'".$conclusion->conclusion."'}";
			}
			$this->request->response = $template;
		}
		
		public function action_newconclusion(){
			$this->request->response = $this->newTemplate("Conclusiones","/diastole/analysis/saveconclusion")->render();
		}
		
		
		public function action_saveconclusion(){
			$data = array();
			$data['conclusion_name'] = $_POST['template_name']; 
			$data['conclusion'] = $_POST['template_description']; 
			
			if (($applicable = $_POST['applicable']) == "all"){	$data['female'] = 1;$data['male'] = 1;}
			elseif ($applicable == "male"){$data['female'] = 0;$data['male'] = 1;}
			else{ $data['female'] = 1;$data['male'] = 0;}
						
			$id = Helper_Service::factory("conclusion")->save(0,$data);
			$this->request->response = $this->savedTemplateResponse(true,"Plantilla de Conclusión Guardada con Exito")->render();
		}
		
		
		public function action_savereportconclusion(){
			$id_analysis = $this->request->param("id");
			$conclusion = $_POST["content"];
			$this->request->response = Helper_Service::factory("analysis",$id_analysis)->getReport()->saveConclusion($conclusion);
		}
		
		
		/*************************************************************************************************/
		private function factoryTemplate($title, $templates_list, $feed_url, $preview_url, $add_url, $content_save_url, $current_content){
			$view = View::factory("analysis/content-report-template");
			$view->templates = $templates_list;
			$view->template_content_entity = $title;
			$view->templates_feed = $feed_url; 
			$view->preview_feed = $preview_url;
			$view->template_new = $add_url;
			$view->content_save = $content_save_url;
			$view->report_content = $current_content;
			return $view;
		}
		
		private function filteredTemplates($filter="all",$service){
			if ($filter == "all") $filtered = $service->getAll();
			else if ($filter == "male")	$filtered =$service->getMale(); 
			else $filtered = $service->getFemale();
			return $filtered;
		}
		
		private function jsonTemplates($dataset){ return "[".implode(",",$dataset)."]";}
				
		private function newTemplate($template_name, $save_url){
			$template_form = View::factory("components/new-report-template");
			$template_form->template_entity = $template_name;
			$template_form->template_save_url = $save_url;  
			return $template_form;
		}
		
		private function savedTemplateResponse($ok,$response){
			$template_response = View::factory("components/saved-report-template");
			$template_response->responseText = $response;
			return $template_response;
		}
				
		/*Pestaña Reportes*/
		private function createReportData($id_analysis){
			$analysis = Helper_Service::factory("analysis",$id_analysis);
			$clinicalData = $analysis->getClinicalData();
			$patient = $analysis->getPatient();
			$results = $analysis->getResults();
			$report = $analysis->getReport();

			$reportData = array();
			$reportData["patient"] = array("age"=>$patient->getAge(),"fullname"=>$patient->getFullname(),"pd"=>$clinicalData->getDiastolicPressure(),"ps"=>$clinicalData->getSystolicPressure(),"smokes"=>$patient->smokes(),"weight"=>$clinicalData->getWeight());
			$reportData["parameter_values"] = array("aod"=>$results->getDiastolicWaveAmp()->value,"aos"=>$results->getSystolicWaveLength()->value,"iar"=>$results->getRadialAugmentation()->value,"imc"=>$clinicalData->calculateIMC(),"fc"=>$results->getHeartRate());
			$reportData["indexes"] = array("iar"=>$report->getIARComment(),"aod"=>$report->getAODComment(),"aos"=>$report->getAOSComment());
			$reportData["medic"] = $analysis->getMedic()->getFullname();
			$reportData["segment_image_url"] = "/diastole/plotter/reportsegment/$id_analysis";
			$reportData["comments"] = $report->getComments();
			$reportData["conclusion"] = $report->getConclusion();
			$reportData["background_family"] = $report->getBackgroundFamily(); 
			$reportData['background_medicines'] = $report->getBackgroundMedicines();
			$reportData['background_pathologies'] = $report->getBackgroundPathologies();
			$reportData['background_surgeries'] = $report->getBackgroundSurgeries();
									
			return $reportData;
		}
		
		
		public function action_preview(){
			$data = $this->createReportData($this->request->param("id"));
			$preview = View::factory("analysis/report-template",$data);
			$this->request->response = $preview->render();
		}
		
		public function action_rawsignal(){}
						
				
		
		/*Pestaña Exportar Datos*/
		public function action_export(){
			$export_view = View::factory("analysis/export")->set("id_analysis",$this->request->param("id"));
			$this->request->response = $export_view->render();
		}
		
		public function action_exportReport(){
			$id_analysis = $this->request->param("id");
			$data = $this->createReportData($id_analysis);
			$preview = View::factory("analysis/report-template",$data);

			$styles = array(
				'media/css/mf4_layout2_setup.css' => 'screen, projection, print',
				'media/css/mf4_layout2_text.css'  => 'screen, projection, print',
				'media/css/report_preview.css'=>'screen,projection,print'
			);
			
			$print_preview = View::factory("analysis/report-print-preview");
			$print_preview->title = "Impresión Informe";
			$print_preview->styles = $styles;			
			$print_preview->report_content = $preview->render();
			
			$this->request->response = $print_preview->render();
				
		}
		
		public function action_exportAnalysis(){
			$id_analysis = $this->request->param("id");
			$analysis = Helper_Service::factory("analysis",$id_analysis);
			$analysis->export();
		}
		
	} 
// End Analysis
?>

